<template>
  <div class="badge-list">
    <el-card>
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="header-left">
          <h2>徽章管理</h2>
          <p class="description">管理音乐节相关的徽章和成就系统</p>
        </div>
        <div class="header-right">
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_CREATE)"
            type="primary" 
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            添加徽章
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索徽章名称、描述等"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="searchForm.type" placeholder="选择类型" clearable>
              <el-option 
                v-for="option in BADGE_TYPE_OPTIONS" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value" 
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 徽章列表 -->
      <el-table
        v-loading="loading"
        :data="badgeList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="图标" width="100">
          <template #default="{ row }">
            <div class="badge-icon-wrapper">
              <img 
                v-if="row.icon" 
                :src="row.icon" 
                :alt="row.name"
                class="badge-icon"
                @click="previewIcon(row.icon)"
              />
              <div v-else class="no-icon">
                <el-icon><Picture /></el-icon>
                <span>无图标</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.type" :type="getBadgeTypeTagType(row.type)">
              {{ getBadgeTypeText(row.type) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="获得人数" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.earnedCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_READ)"
              size="small" 
              @click="viewBadge(row)"
            >
              查看
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_UPDATE)"
              size="small" 
              type="primary" 
              @click="editBadge(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_UPDATE)"
              size="small" 
              type="success" 
              @click="showIconUpload(row)"
            >
              图标
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_DELETE)"
              size="small" 
              type="danger" 
              @click="deleteBadge(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入徽章名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入徽章描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="选择徽章类型" clearable>
            <el-option 
              v-for="option in BADGE_TYPE_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="条件类型" prop="conditionType">
          <el-select v-model="formData.conditionType" placeholder="选择条件类型" clearable>
            <el-option 
              v-for="option in BADGE_CONDITION_TYPE_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="条件值" prop="conditionValue">
          <el-input-number
            v-model="formData.conditionValue"
            :min="1"
            :max="999999"
            placeholder="请输入条件值"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图标上传对话框 -->
    <el-dialog
      v-model="iconDialogVisible"
      title="徽章图标管理"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="icon-upload-section">
        <div class="current-icon" v-if="currentBadge?.icon">
          <h4>当前图标</h4>
          <img :src="currentBadge.icon" :alt="currentBadge.name" class="current-icon-img" />
          <div class="icon-actions">
            <el-button type="danger" size="small" @click="deleteBadgeIcon">删除图标</el-button>
          </div>
        </div>
        
        <div class="upload-section">
          <h4>上传新图标</h4>
          <el-upload
            ref="uploadRef"
            :action="''"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept="image/*"
            :limit="1"
          >
            <el-button type="primary" :loading="uploadLoading">选择图标文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 JPG、PNG、GIF 格式，文件大小不超过 2MB
              </div>
            </template>
          </el-upload>
          
          <div v-if="selectedFile" class="selected-file">
            <img :src="previewUrl" :alt="selectedFile.name" class="preview-img" />
            <div class="file-info">
              <p><strong>文件名：</strong>{{ selectedFile.name }}</p>
              <p><strong>文件大小：</strong>{{ formatFileSize(selectedFile.size) }}</p>
            </div>
            <el-button type="success" :loading="uploadLoading" @click="uploadIcon">上传图标</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 图标预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[previewImageUrl]"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import { contentApi } from '@/api'
import { useUserStore } from '@/stores/user'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import { BADGE_TYPE_OPTIONS, BADGE_CONDITION_TYPE_OPTIONS } from '@/constants/common'
import { formatDate } from '@/utils/format'
import type { Badge, CreateBadgeRequest, UpdateBadgeRequest } from '@/types'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const badgeList = ref<Badge[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  search: '',
  type: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentId = ref<number | null>(null)
const submitLoading = ref(false)
const formRef = ref()

const formData = reactive({
  name: '',
  description: '',
  type: '',
  conditionType: '',
  conditionValue: null as number | null
})

const formRules = {
  name: [
    { required: true, message: '请输入徽章名称', trigger: 'blur' },
    { min: 2, max: 100, message: '名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入徽章描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 图标上传相关
const iconDialogVisible = ref(false)
const currentBadge = ref<Badge | null>(null)
const selectedFile = ref<File | null>(null)
const previewUrl = ref('')
const uploadLoading = ref(false)
const uploadRef = ref()

// 图标预览相关
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 获取徽章列表
const fetchBadges = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await contentApi.badges.getList(params)
    badgeList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取徽章列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchBadges()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    type: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchBadges()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchBadges()
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true
  dialogTitle.value = '创建徽章'
  isEdit.value = false
  currentId.value = null
  formData.name = ''
  formData.description = ''
  formData.type = ''
  formData.conditionType = ''
  formData.conditionValue = null
}

// 编辑徽章
const editBadge = (badge: Badge) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑徽章'
  isEdit.value = true
  currentId.value = badge.id
  formData.name = badge.name
  formData.description = badge.description || ''
  formData.type = badge.type || ''
  formData.conditionType = badge.conditionType || ''
  formData.conditionValue = badge.conditionValue
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value && currentId.value) {
      await contentApi.badges.update(currentId.value, formData as UpdateBadgeRequest)
      ElMessage.success('更新成功')
    } else {
      await contentApi.badges.create(formData as CreateBadgeRequest)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchBadges()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 查看徽章详情
const viewBadge = async (badge: Badge) => {
  try {
    const response = await contentApi.badges.getById(badge.id)
    const detailBadge = response.data.badge
    
    ElMessageBox.alert(
      `
      <div style="text-align: left;">
        <h3>${detailBadge.name}</h3>
        <p><strong>描述：</strong>${detailBadge.description || '无'}</p>
        <p><strong>类型：</strong>${detailBadge.type || '未设置'}</p>
        <p><strong>条件类型：</strong>${detailBadge.conditionType || '未设置'}</p>
        <p><strong>条件值：</strong>${detailBadge.conditionValue || '未设置'}</p>
        <p><strong>获得人数：</strong>${detailBadge.earnedCount || 0}</p>
        <p><strong>创建时间：</strong>${formatDate(detailBadge.createdAt)}</p>
      </div>
      `,
      '徽章详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      }
    )
  } catch (error) {
    ElMessage.error('获取徽章详情失败')
  }
}

// 删除徽章
const deleteBadge = async (badge: Badge) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除徽章 "${badge.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contentApi.badges.delete(badge.id)
    ElMessage.success('删除成功')
    fetchBadges()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 显示图标上传对话框
const showIconUpload = (badge: Badge) => {
  currentBadge.value = badge
  iconDialogVisible.value = true
  selectedFile.value = null
  previewUrl.value = ''
}

// 处理文件选择
const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
  previewUrl.value = URL.createObjectURL(file.raw)
}

// 上传图标
const uploadIcon = async () => {
  if (!selectedFile.value || !currentBadge.value) return
  
  try {
    uploadLoading.value = true
    await contentApi.badges.uploadIcon(currentBadge.value.id, selectedFile.value)
    ElMessage.success('图标上传成功')
    
    // 刷新徽章列表
    await fetchBadges()
    
    // 更新当前徽章信息
    const response = await contentApi.badges.getById(currentBadge.value.id)
    currentBadge.value = response.data.badge
    
    // 清空选择
    selectedFile.value = null
    previewUrl.value = ''
  } catch (error) {
    ElMessage.error('图标上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 删除徽章图标
const deleteBadgeIcon = async () => {
  if (!currentBadge.value) return
  
  try {
    await ElMessageBox.confirm(
      '确定要删除这个徽章图标吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contentApi.badges.deleteIcon(currentBadge.value.id)
    ElMessage.success('图标删除成功')
    
    // 刷新徽章列表
    await fetchBadges()
    
    // 更新当前徽章信息
    const response = await contentApi.badges.getById(currentBadge.value.id)
    currentBadge.value = response.data.badge
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('图标删除失败')
    }
  }
}

// 预览图标
const previewIcon = (url: string) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取徽章类型标签类型
const getBadgeTypeTagType = (type: string) => {
  switch (type) {
    case 'ACHIEVEMENT':
      return 'success'
    case 'COLLECTION':
      return 'info'
    case 'SPECIAL':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取徽章类型文本
const getBadgeTypeText = (type: string) => {
  const typeOption = BADGE_TYPE_OPTIONS.find(option => option.value === type)
  return typeOption ? typeOption.label : '未知类型'
}

// 初始化
onMounted(() => {
  fetchBadges()
})
</script>

<style scoped>
.badge-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.badge-icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.badge-icon {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.badge-icon:hover {
  transform: scale(1.1);
}

.no-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.no-icon .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

/* 图标上传对话框样式 */
.icon-upload-section {
  padding: 20px 0;
}

.current-icon {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: center;
}

.current-icon h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.current-icon-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 15px;
}

.icon-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.upload-section {
  text-align: center;
}

.upload-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.selected-file {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 15px;
}

.file-info {
  margin-bottom: 15px;
  text-align: left;
}

.file-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style> 